//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.ty.pdm.system.workFlow.listener.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.spring.SpringUtil;

import com.alibaba.fastjson.JSONObject;
import com.hustcad.plm.basic.log.LogEventEnum;
import com.hustcad.plm.basic.util.TyCommonExtUtil;
import com.hustcad.plm.basic.util.TyplmEntityBaseUtil;
import com.hustcad.plm.caddocapi.service.cadstruct.TyplmCadStructService;
import com.hustcad.plm.pdm.audit.model.dto.TyplmAuditChangeLCLogDTO;
import com.hustcad.plm.pdm.audit.util.TyplmAuditLogUtil;
import com.hustcad.plm.pdm.caddoc.model.dto.cadstruct.CadStructConditionDTO;
import com.hustcad.plm.pdm.caddoc.model.dto.cadstruct.CadStructFilterDTO;
import com.hustcad.plm.pdm.caddoc.model.vo.cadstruct.CadStructFilterVO;
import com.hustcad.plm.pdm.common.model.dto.EntityMessageDTO;
import com.hustcad.plm.pdm.common.model.dto.search.SearchConditionDTO;
import com.hustcad.plm.pdm.common.model.vo.search.ResultEntityVO;
import com.hustcad.plm.pdm.common.service.entity.TyplmEntityBaseService;
import com.hustcad.plm.pdm.common.util.CommonUtil;
import com.hustcad.plm.pdm.common.util.TyplmPermissionsUtil;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocDetails;
import com.hustcad.plm.pdm.enumeration.service.TyplmLocalePropertyValueService;
import com.hustcad.plm.pdm.file.util.QueryDownloadDocUtil;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObject;
import com.hustcad.plm.pdm.flowbusiness.model.entity.FlowObjectPackageLink;
import com.hustcad.plm.pdm.flowbusiness.service.TyplmFlowObjectPackageLinkService;
import com.hustcad.plm.pdm.folder.model.constant.FolderQueryConstant;
import com.hustcad.plm.pdm.lifestage.mapper.TyplmPhaseSuccessionMapper;
import com.hustcad.plm.pdm.lifestage.model.constant.LifeStageErrorCodeEnum;
import com.hustcad.plm.pdm.lifestage.model.dto.*;
import com.hustcad.plm.pdm.lifestage.model.vo.LifeCycleStageVO;
import com.hustcad.plm.pdm.lifestage.service.TyplmCommonLifecycleService;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifeCycleHistoryService;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifecycleStageService;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifecycleStageTemplateService;
import com.hustcad.plm.pdm.lifestage.service.TyplmLifecycleTemplateService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartRelObjectService;
import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.modeling.model.dto.TyplmGeneralOperationDTO;

import com.hustcad.plm.pdm.mpmlink.service.TyplmMpmWorkFlowAdaptationService;
import com.hustcad.plm.pdm.partbom.dto.ChildPartsFiltersDTO;
import com.hustcad.plm.pdm.partbom.dto.PartBomTree;
import com.hustcad.plm.pdm.partbom.service.TyplmPartBomService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartDescribeLinkService;
import com.hustcad.plm.pdm.partbom.service.TyplmPartService;
import com.hustcad.plm.pdm.partbom.vo.PartBomTreeByFilterVO;
import com.hustcad.plm.pdm.partbom.vo.PartDetailsVO;
import com.hustcad.plm.pdm.partbom.vo.QueryDescribeObjVO;
import com.hustcad.plm.pdm.preference.util.TyplmPreferenceValueUtil;

import com.hustcad.plm.pdm.user.service.TyplmTeamForStageService;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.annotion.CustomListenerField;
import com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainer;
import com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService;

import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ty.basic.common.ITyLifeCycleManaged;
import com.ty.basic.common.ITyLockable;
import com.ty.basic.common.ITyUpdator;
import com.ty.basic.entity.CTyEntityBaseDO;
import com.ty.basic.entity.IdentifierEntity;
import com.ty.basic.entity.org.UserDO;

import com.ty.basic.enums.StatusActionEnum;
import com.ty.basic.exception.message.SystemErrorCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.ResponseCodeEnum;
import com.ty.basic.handler.exceptionhandler.exception.TyException;
import com.ty.basic.session.TyAccountContext;
import com.ty.basic.util.TyMessageUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.delegate.TaskListener;
import org.flowable.engine.impl.el.FixedValue;
import org.flowable.task.service.delegate.DelegateTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;


@CustomListener(
        category = "永续发布流程通用",
        description = "全生命周期阶段变更"
)
public class JsyxdlLifeCycleOperatorListener implements ExecutionListener, TaskListener {
    private static final Logger log = LoggerFactory.getLogger(LifeCycleOperatorListener.class);
    private static final long serialVersionUID = 347348832L;
    @CustomListenerField(
            description = "目标生命周期阶段key",
            defaultValue = "",
            required = true
    )
    private FixedValue targetStatusKey;

    @CustomListenerField(
            description = "源生命周期状态",
            defaultValue = "",
            required = true
    )
    private FixedValue srcStatus;

    @CustomListenerField(
            description = "所有子件变更",
            defaultValue = "",
            required = true
    )
    private FixedValue scopeChange;

    @CustomListenerField(
            description = "关联的主控图纸",
            defaultValue = "",
            required = true
    )
    private FixedValue mainControlDrawing;
    @CustomListenerField(
            description = "参考文档",
            defaultValue = "",
            required = true
    )
    private FixedValue referenceDocument;
    @CustomListenerField(
            description = "描述文档",
            defaultValue = "",
            required = true
    )
    private FixedValue describeDocument;
    @CustomListenerField(
            description = "图纸关联的零部件",
            defaultValue = "",
            required = true
    )
    private FixedValue componentsAssociatedDrawings;
    @CustomListenerField(
            description = "参考和描述文档关联的零部件",
            defaultValue = "",
            required = true
    )
    private FixedValue referenceDescribeAssociatedDrawings;



    public void notify(DelegateExecution delegateExecution) {
        try {
            String workFlowContainerId = delegateExecution.getProcessInstanceBusinessKey();
            if (StringUtils.isBlank(workFlowContainerId)) {
                workFlowContainerId = delegateExecution.getVariable("workFlowContainerId").toString();
            }

            this.setFlowObjectLifeCycle(workFlowContainerId);
        } catch (Exception var3) {
            log.error("监听JsyxdlLifeCycleOperatorListener异常：", var3);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(var3.getMessage());
        }
    }

    private void setFlowObjectLifeCycle(String workFlowContainerId) {
        TyplmWorkFlowContainerService typlmWorkFlowContainerService = SpringUtil.getBean(
                TyplmWorkFlowContainerService.class);
        WorkFlowContainer workFlowContainer = typlmWorkFlowContainerService.selectOneByOid(
                new BigInteger(workFlowContainerId));
        String baseObjectOtype = workFlowContainer.getBaseObjectOtype();
        if ("com.ty.entity.workFlow.FlowObjectPackage".equals(baseObjectOtype)) {
            List<String> selectPreferenceValueList = Collections.singletonList("flow_updatestate_all");
            TyplmPreferenceValueUtil typlmPreferenceValueUtil = SpringUtil.getBean(TyplmPreferenceValueUtil.class);
            Map<String, Object> preferenceCollectRulesMap = typlmPreferenceValueUtil.readPreferenceValueByKeywords(
                    selectPreferenceValueList);
            boolean flowUpdatestateAll = QueryDownloadDocUtil.getBooleanValueByObject(
                    preferenceCollectRulesMap.get("flow_updatestate_all"));
            String key = "N";
            if (flowUpdatestateAll) {
                key = "Y";
            }

            TyplmFlowObjectPackageLinkService typlmFlowObjectPackageLinkService = SpringUtil.getBean(
                    TyplmFlowObjectPackageLinkService.class);
            List<FlowObjectPackageLink> listByPackage = typlmFlowObjectPackageLinkService.getListByPackage(
                    workFlowContainer.getBaseObjectOid(), workFlowContainer.getBaseObjectOtype());
            List<FlowObject> flowObjectList = typlmFlowObjectPackageLinkService.batchUpdateLast(listByPackage);
            if (flowObjectList == null) {
                log.info("生命周期阶段变更JsyxdlLifeCycleOperatorListener，获取到的流程对象为空，不处理，请检查数据！");
                return;
            }

            if (this.targetStatusKey == null) {
                log.info(
                        "生命周期阶段变更JsyxdlLifeCycleOperatorListener，监听参数targetStatusKey为空，不处理，请给对应监听参数设置值！");
                return;
            }

            try {
                ModifyTheTypeJudgment(key, flowObjectList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void setProcessObjectLife(FlowObject flowObject, String key, String lifeCycleCode,
                                      List<EntityLifeCycleDTO> entityLifeCycleList) {
        if (key.equals("Y") && (flowObject.getRefObjectOtype().equals(
                "ty.inteplm.mpm.CTyMPMProcessPlan") || flowObject.getRefObjectOtype().equals(
                "ty.inteplm.mpm.CTyMPMOperation"))) {
            TyplmMpmWorkFlowAdaptationService tymMpmWorkFlowAdaptationService = SpringUtil.getBean(
                    TyplmMpmWorkFlowAdaptationService.class);
            List<JSONObject> list = new ArrayList();
            TyplmGeneralOperationDTO goDTO = new TyplmGeneralOperationDTO();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("otype", flowObject.getRefObjectOtype());
            jsonObject.put("oid", flowObject.getRefObjectOid());
            List<JSONObject> currentObj = new ArrayList();
            currentObj.add(jsonObject);
            goDTO.setCurrentObj(currentObj);
            tymMpmWorkFlowAdaptationService.getAllObjWorkFlow(goDTO, list);
            if (CollUtil.isNotEmpty(list)) {
                Iterator var10 = list.iterator();

                while (var10.hasNext()) {
                    JSONObject object = (JSONObject) var10.next();
                    EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                    entityLifeCycleDTO.setOid(object.getBigInteger("oid"));
                    entityLifeCycleDTO.setOtype(this.parseObjOtype(object.getString("otype")));
                    entityLifeCycleDTO.setLifeCycleStageKey(lifeCycleCode);
                    entityLifeCycleList.add(entityLifeCycleDTO);
                }
            }
        }

    }

    private String parseObjOtype(String type) {
        String result = "";
        if (StringUtils.isEmpty(type)) {
            return result;
        } else {
            String[] otype = type.split("\\|");
            result = otype[0];
            return result;
        }
    }

    public void notify(DelegateTask delegateTask) {
        try {
            BigInteger workFlowContainerId = new BigInteger(delegateTask.getVariable("workFlowContainerId").toString());
            this.setFlowObjectLifeCycle(workFlowContainerId.toString());
        } catch (Exception var3) {
            log.error("监听JsyxdlLifeCycleOperatorListener异常：", var3);
            throw SystemErrorCodeEnum.WORK_FLOW_CONTENT_ERROR.getException(var3.getMessage());
        }
    }

    /**
     * 判断参数，放行生命周期修改
     */
    public void ModifyTheTypeJudgment(String key, List<FlowObject> flowObjectList) throws Exception {
        TyplmCommonLifecycleService typlmCommonLifecycleService = SpringUtil.getBean(TyplmCommonLifecycleService.class);
        TyplmLocalePropertyValueService typlmLocalePropertyValueService = SpringUtil.getBean(
                TyplmLocalePropertyValueService.class);
        TyplmPartService typlmPartService = SpringUtil.getBean(                TyplmPartService.class);
        TyplmDocumentService typlmDocumentService = SpringUtil.getBean(                TyplmDocumentService.class);
        if (this.targetStatusKey != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);
                if(this.srcStatus!=null){
                    if("ty.inteplm.part.CTyPart".equals(flowObject.getRefObjectOtype())){
                        BigInteger oid = flowObject.getRefObjectOid();
                        String oType = flowObject.getRefObjectOtype();
                        PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);
                        if(this.srcStatus.getExpressionText().equals(partDetailsVO.getLifecycleStateKey())==false){
                            continue;
                        }
                    }
                    else if("ty.inteplm.cad.CTyCADDoc".equals(flowObject.getRefObjectOtype())){
                        BigInteger oid = flowObject.getRefObjectOid();
                        String oType = flowObject.getRefObjectOtype();
                        DocDetails docDetails = typlmDocumentService.queryDocDetails(oid, oType);

                        if(this.srcStatus.getExpressionText().equals(docDetails.getLifecycleStateKey())==false){
                            continue;
                        }
                    }
                    else if("ty.inteplm.doc.CTyDoc".equals(flowObject.getRefObjectOtype())){
                        BigInteger oid = flowObject.getRefObjectOid();
                        String oType = flowObject.getRefObjectOtype();
                        DocDetails docDetails = typlmDocumentService.queryDocDetails(oid, oType);

                        if(this.srcStatus.getExpressionText().equals(docDetails.getLifecycleStateKey())==false){
                            continue;
                        }
                    }
                }


                EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                entityLifeCycleDTO.setOid(flowObject.getRefObjectOid());
                entityLifeCycleDTO.setOtype(flowObject.getRefObjectOtype());
                entityLifeCycleDTO.setLifeCycleStageKey(this.targetStatusKey.getExpressionText());
                entityLifeCycleList.add(entityLifeCycleDTO);
                this.setProcessObjectLife(flowObject, key, this.targetStatusKey.getExpressionText(),
                                          entityLifeCycleList);
            }

            Map<String, String> localMap = typlmLocalePropertyValueService.queryLocaleValueByItem(new ArrayList(),
                                                                                                  "LifeCycleState",
                                                                                                  TyCommonExtUtil.getFrontLanguage());
            entityLifeCycleList.forEach((entityLifeCycleDTOx) -> {
                TyplmAuditChangeLCLogDTO typlmAuditChangeLCLogDTO = new TyplmAuditChangeLCLogDTO();
                typlmAuditChangeLCLogDTO.setNewLCKey(entityLifeCycleDTOx.getLifeCycleStageKey());
                typlmAuditChangeLCLogDTO.setOid(entityLifeCycleDTOx.getOid());
                typlmAuditChangeLCLogDTO.setOtype(entityLifeCycleDTOx.getOtype());
                TyplmAuditLogUtil.info(typlmAuditChangeLCLogDTO, LogEventEnum.CHANGE_LC_STATE,
                                       String.format("流程中生命周期状态 变为 %s",
                                                     localMap.get(entityLifeCycleDTOx.getLifeCycleStageKey())));
            });
            typlmCommonLifecycleService.batchUpdateEntityLifecycle(entityLifeCycleList, true, true);
        }
        if (this.scopeChange != null && "是".equals(this.scopeChange.getExpressionText())) {
            childLifeStatus(key, flowObjectList);
        }
        if (this.referenceDocument != null && "是".equals(this.referenceDocument.getExpressionText())) {
            referenceDocumentLifeStatus(key, flowObjectList);
        }
        if (this.describeDocument != null && "是".equals(this.describeDocument.getExpressionText())) {
            describeDocumentLifeStatus(key, flowObjectList);
        }
        if (this.mainControlDrawing != null && "是".equals(this.mainControlDrawing.getExpressionText())) {
            mainControlDrawingLifeStatus(key, flowObjectList);
        }
        if (this.componentsAssociatedDrawings != null && "是".equals(
                this.componentsAssociatedDrawings.getExpressionText())) {
            componentsAssociatedDrawingsLifeStatus(key, flowObjectList);
        }
        if (this.referenceDescribeAssociatedDrawings != null && "是".equals(
                this.referenceDescribeAssociatedDrawings.getExpressionText())) {
            referenceDescribeAssociatedDrawingsLifeStatus(key, flowObjectList);
        }
    }

    /**
     * 修改所有子级零部件生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void childLifeStatus(String key, List<FlowObject> flowObjectList) throws Exception {
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPartService typlmPartService = (TyplmPartService) SpringUtil.getBean(
                TyplmPartService.class);
        TyplmLifecycleTemplateService typlmLifecycleTemplateService=SpringUtil.getBean(
                TyplmLifecycleTemplateService.class);
        TyplmCadStructService typlmCadStructService=SpringUtil.getBean(
                TyplmCadStructService.class);

        if (typlmPartBomService != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);

                if("ty.inteplm.part.CTyPart".equals(flowObject.getRefObjectOtype())){
                    com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                    expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                    ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                    childPartsFiltersDTO.setBaseLineOid("");
                    childPartsFiltersDTO.setDate("");
                    childPartsFiltersDTO.setExpandCondition("latest");
                    childPartsFiltersDTO.setLifecycleStateKey("");
                    childPartsFiltersDTO.setPurposeOfBom("");
                    childPartsFiltersDTO.setSpareBom("");
                    childPartsFiltersDTO.setView(flowObject.getView());
                    List<ChildPartsFiltersDTO> list = new ArrayList<>();
                    list.add(childPartsFiltersDTO);
                    expandBomTreeByFilterDTO.setConditions(list);

                    expandBomTreeByFilterDTO.setExpandLevel("N");
                    expandBomTreeByFilterDTO.setFatherNumber(flowObject.getRefObjectNumber());
                    expandBomTreeByFilterDTO.setFatherOid(String.valueOf(flowObject.getRefObjectOid()));
                    expandBomTreeByFilterDTO.setFatherOtype(flowObject.getRefObjectOtype());
                    expandBomTreeByFilterDTO.setFilterMode("0");
                    expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                    expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                    expandBomTreeByFilterDTO.setIsApplyRoot(false);
                    expandBomTreeByFilterDTO.setIsFilterAttr(false);
                    expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                    expandBomTreeByFilterDTO.setIsNestedTree(false);
                    expandBomTreeByFilterDTO.setIsQueryIBA(true);


                    PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                                Boolean.TRUE);


                    for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                        PartBomTree partBomTree = result.getPartBomTreeList().get(y);
                        if (partBomTree.getOid() != BigInteger.valueOf(0L)) {

                            BigInteger oid = new BigInteger(partBomTree.getPartoid());
                            String oType = partBomTree.getPartotype();
                            PartDetailsVO partDetailsVO = typlmPartService.queryPartDetails(oid, oType);


                            if(this.srcStatus==null){
                                if ("RELEASED".equals(partDetailsVO.getLifecycleStateKey())) {
                                    continue;
                                }
                            }
                            else{
                                if(!partDetailsVO.getLifecycleStateKey().equals(this.srcStatus.getExpressionText())){
                                    continue;
                                }
                            }


                            IdentifierEntity identifierEntity=new IdentifierEntity();
                            identifierEntity.setOid(new BigInteger(partDetailsVO.getOid()));
                            identifierEntity.setOtype(partDetailsVO.getOtype());
                            List<IdentifierEntity> identifierEntities=new ArrayList<>();
                            identifierEntities.add(identifierEntity);

                            List<ObjLifeStateDTO> lifeList=typlmLifecycleTemplateService.batchQueryEntityLifecycleState(identifierEntities);
                            boolean add=false;
                            if(lifeList.size()>0){
                                for(int z=0;z<lifeList.get(0).getLifecycleList().size();z++){
                                    if(this.targetStatusKey.getExpressionText().equals(lifeList.get(0).getLifecycleList().get(z).getCode())){
                                        add=true;
                                        break;
                                    }
                                }
                            }
                            if(!add) continue;

                            FlowObject childFlowObject = new FlowObject();

                            childFlowObject.setRefObjectOid(new BigInteger(partBomTree.getPartoid()));
                            childFlowObject.setRefObjectOtype(partBomTree.getPartotype());
                            childFlowObject.setRefObjectView(partBomTree.getView());

                            EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                            entityLifeCycleDTO.setOid(childFlowObject.getRefObjectOid());
                            entityLifeCycleDTO.setOtype(childFlowObject.getRefObjectOtype());
                            entityLifeCycleDTO.setLifeCycleStageKey(this.targetStatusKey.getExpressionText());
                            entityLifeCycleList.add(entityLifeCycleDTO);
                        }
                    }
                }

            }
            if(entityLifeCycleList.size()>0){
                LifeCycleDTO lifeCycleDTO = new LifeCycleDTO();
                lifeCycleDTO.setEntityLifeCycleDTOS(entityLifeCycleList);
                lifeCycleDTO.setExcludeException(false);

                List<EntityLifeCycleDTO> entityLifeCycleDTOS = lifeCycleDTO.getEntityLifeCycleDTOS();
                batchUpdateEntityLifecycle(entityLifeCycleDTOS, false, false, false);
            }

        }
    }

    /**
     * 修改关联主控图纸生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void mainControlDrawingLifeStatus(String key, List<FlowObject> flowObjectList) throws Exception {
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPdmPartRelObjectService typlmPdmPartRelObjectService = SpringUtil.getBean(
                TyplmPdmPartRelObjectService.class);
        TyplmCadStructService typlmCadStructService=SpringUtil.getBean(
                TyplmCadStructService.class);
        if (typlmPartBomService != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);
                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(flowObject.getView());
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("N");
                expandBomTreeByFilterDTO.setFatherNumber(flowObject.getRefObjectNumber());
                expandBomTreeByFilterDTO.setFatherOid(String.valueOf(flowObject.getRefObjectOid()));
                expandBomTreeByFilterDTO.setFatherOtype(flowObject.getRefObjectOtype());
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(false);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);


                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);

                Map<String,Object> cadMap=new HashMap<>();

                for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                    PartBomTree partBomTree = result.getPartBomTreeList().get(y);

                    List<DocDetails> docDetailsList = typlmPdmPartRelObjectService.queryPartRelCadInfo(
                            new BigInteger(partBomTree.getPartoid()));

                    for (int i = 0; i < docDetailsList.size(); i++) {
                        DocDetails docDetails = docDetailsList.get(i);

                        FlowObject childFlowObject = new FlowObject();
                        childFlowObject.setRefObjectOid(new BigInteger(docDetails.getOid()));
                        childFlowObject.setRefObjectOtype(docDetails.getOtype());

                        CadStructFilterDTO filterDTO = new CadStructFilterDTO();
                        filterDTO.setLevel("N");
                        filterDTO.setTopLevel(false);
                        List<BigInteger> denList=new ArrayList<>();
                        denList.add(new BigInteger(docDetails.getOid()));
                        filterDTO.setIdList(denList);

                        List<CadStructConditionDTO> conditionDTOList=new ArrayList<>();
                        CadStructConditionDTO cadStructConditionDTO=new CadStructConditionDTO();
                        cadStructConditionDTO.setQueryType("asstored");
                        cadStructConditionDTO.setLifecycleState("");
                        cadStructConditionDTO.setBaseLineOid(null);
                        conditionDTOList.add(cadStructConditionDTO);
                        filterDTO.setConditionDTOList(conditionDTOList);

                        SearchConditionDTO searchCondition=new SearchConditionDTO();
                        searchCondition.setPageNum(1);
                        searchCondition.setPageSize(99999999);
                        searchCondition.setNeedIBA(false);
                        searchCondition.setNeedThumbnailFile(false);
                        searchCondition.setSearchType(0);
                        searchCondition.setColumns(new ArrayList<>());
                        filterDTO.setSearchCondition(searchCondition);
                        List<CadStructFilterVO> cadList=typlmCadStructService.queryCadStructByFilterCondition(filterDTO);

                        for(int h=0;h<cadList.size();h++){
                            CadStructFilterVO cadStructFilterVO=cadList.get(h);
                            if(cadMap.containsKey(cadStructFilterVO.getResultEntityVo().getOid().toString())==false){
                                EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                                entityLifeCycleDTO.setOid(cadStructFilterVO.getResultEntityVo().getOid());
                                entityLifeCycleDTO.setOtype(cadStructFilterVO.getResultEntityVo().getOtype());
                                entityLifeCycleDTO.setLifeCycleStageKey(this.targetStatusKey.getExpressionText());
                                entityLifeCycleList.add(entityLifeCycleDTO);
                                this.setProcessObjectLife(childFlowObject, key, this.targetStatusKey.getExpressionText(),
                                                          entityLifeCycleList);
                                cadMap.put(cadStructFilterVO.getResultEntityVo().getOid().toString(),1);
                            }
                        }

                    }
                }
            }

            if (entityLifeCycleList.size() > 0) {
                LifeCycleDTO lifeCycleDTO = new LifeCycleDTO();
                lifeCycleDTO.setEntityLifeCycleDTOS(entityLifeCycleList);
                lifeCycleDTO.setExcludeException(false);

                List<EntityLifeCycleDTO> entityLifeCycleDTOS = lifeCycleDTO.getEntityLifeCycleDTOS();
                batchUpdateEntityLifecycle(entityLifeCycleDTOS, false, false, false);
            }
        }
    }

    /**
     * 修改参考文档生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void referenceDocumentLifeStatus(String key, List<FlowObject> flowObjectList) throws Exception {


        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPdmPartService typlmPdmPartService = SpringUtil.getBean(
                TyplmPdmPartService.class);

        if (typlmPartBomService != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);

                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(flowObject.getView());
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("N");
                expandBomTreeByFilterDTO.setFatherNumber(flowObject.getRefObjectNumber());
                expandBomTreeByFilterDTO.setFatherOid(String.valueOf(flowObject.getRefObjectOid()));
                expandBomTreeByFilterDTO.setFatherOtype(flowObject.getRefObjectOtype());
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(false);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);


                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);


                for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                    PartBomTree partBomTree = result.getPartBomTreeList().get(y);

                    List<DocDetails> jsonList = typlmPdmPartService.getPartLinkReferenceDoc(partBomTree.getPartoid());
                    for (int i = 0; i < jsonList.size(); i++) {
                        FlowObject childFlowObject = new FlowObject();
                        childFlowObject.setRefObjectOid(new BigInteger(jsonList.get(i).getOid()));
                        childFlowObject.setRefObjectOtype(jsonList.get(i).getOtype());

                        EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                        entityLifeCycleDTO.setOid(childFlowObject.getRefObjectOid());
                        entityLifeCycleDTO.setOtype(childFlowObject.getRefObjectOtype());
                        entityLifeCycleDTO.setLifeCycleStageKey(this.targetStatusKey.getExpressionText());
                        entityLifeCycleList.add(entityLifeCycleDTO);
                        this.setProcessObjectLife(childFlowObject, key, this.targetStatusKey.getExpressionText(),
                                                  entityLifeCycleList);
                    }

                }


            }
            if (entityLifeCycleList.size() > 0) {
                LifeCycleDTO lifeCycleDTO = new LifeCycleDTO();
                lifeCycleDTO.setEntityLifeCycleDTOS(entityLifeCycleList);
                lifeCycleDTO.setExcludeException(false);

                List<EntityLifeCycleDTO> entityLifeCycleDTOS = lifeCycleDTO.getEntityLifeCycleDTOS();
                batchUpdateEntityLifecycle(entityLifeCycleDTOS, false, false, false);
            }

        }

    }

    /**
     * 修改描述文档生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void describeDocumentLifeStatus(String key, List<FlowObject> flowObjectList) throws Exception {
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmPartDescribeLinkService typlmPartDescribeLinkService = SpringUtil.getBean(
                TyplmPartDescribeLinkService.class);

        if (typlmPartBomService != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);
                com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO expandBomTreeByFilterDTO = new com.hustcad.plm.pdm.partbom.dto.ExpandBomTreeByFilterDTO();
                expandBomTreeByFilterDTO.setAttrFilterCondition(new ArrayList<>());

                ChildPartsFiltersDTO childPartsFiltersDTO = new ChildPartsFiltersDTO();
                childPartsFiltersDTO.setBaseLineOid("");
                childPartsFiltersDTO.setDate("");
                childPartsFiltersDTO.setExpandCondition("latest");
                childPartsFiltersDTO.setLifecycleStateKey("");
                childPartsFiltersDTO.setPurposeOfBom("");
                childPartsFiltersDTO.setSpareBom("");
                childPartsFiltersDTO.setView(flowObject.getView());
                List<ChildPartsFiltersDTO> list = new ArrayList<>();
                list.add(childPartsFiltersDTO);
                expandBomTreeByFilterDTO.setConditions(list);

                expandBomTreeByFilterDTO.setExpandLevel("N");
                expandBomTreeByFilterDTO.setFatherNumber(flowObject.getRefObjectNumber());
                expandBomTreeByFilterDTO.setFatherOid(String.valueOf(flowObject.getRefObjectOid()));
                expandBomTreeByFilterDTO.setFatherOtype(flowObject.getRefObjectOtype());
                expandBomTreeByFilterDTO.setFilterMode("0");
                expandBomTreeByFilterDTO.setGiveUsesOccurrence("N");
                expandBomTreeByFilterDTO.setIbaColumns(new ArrayList<>());
                expandBomTreeByFilterDTO.setIsApplyRoot(false);
                expandBomTreeByFilterDTO.setIsFilterAttr(false);
                expandBomTreeByFilterDTO.setIsNeedTranEnum(true);
                expandBomTreeByFilterDTO.setIsNestedTree(false);
                expandBomTreeByFilterDTO.setIsQueryIBA(true);


                PartBomTreeByFilterVO result = typlmPartBomService.expandBomTreeByFilterNew(expandBomTreeByFilterDTO,
                                                                                            Boolean.TRUE);


                for (int y = 0; y < result.getPartBomTreeList().size(); y++) {
                    PartBomTree partBomTree = result.getPartBomTreeList().get(y);

                    List<IdentifierEntity> identifierEntities = new ArrayList<>();
                    IdentifierEntity identifierEntity = new IdentifierEntity();
                    identifierEntity.setOid(new BigInteger(partBomTree.getPartoid()));
                    identifierEntity.setOtype(partBomTree.getPartotype());
                    identifierEntities.add(identifierEntity);
                    List<QueryDescribeObjVO> describeList = typlmPartDescribeLinkService.queryPartDescribeDoc(
                            identifierEntities);

                    for (int i = 0; i < describeList.size(); i++) {
                        QueryDescribeObjVO queryDescribeObjVO = describeList.get(i);

                        for (int z = 0; z < queryDescribeObjVO.getDescribeObjList().size(); z++) {
                            ResultEntityVO resultEntityVO = queryDescribeObjVO.getDescribeObjList().get(z);
                            FlowObject childFlowObject = new FlowObject();
                            childFlowObject.setRefObjectOid(resultEntityVO.getOid());
                            childFlowObject.setRefObjectOtype(resultEntityVO.getOtype());


                            EntityLifeCycleDTO entityLifeCycleDTO = new EntityLifeCycleDTO();
                            entityLifeCycleDTO.setOid(childFlowObject.getRefObjectOid());
                            entityLifeCycleDTO.setOtype(childFlowObject.getRefObjectOtype());
                            entityLifeCycleDTO.setLifeCycleStageKey(this.targetStatusKey.getExpressionText());
                            entityLifeCycleList.add(entityLifeCycleDTO);
                            this.setProcessObjectLife(childFlowObject, key, this.targetStatusKey.getExpressionText(),
                                                      entityLifeCycleList);
                        }

                    }
                }
            }

            if (entityLifeCycleList.size() > 0) {
                LifeCycleDTO lifeCycleDTO = new LifeCycleDTO();
                lifeCycleDTO.setEntityLifeCycleDTOS(entityLifeCycleList);
                lifeCycleDTO.setExcludeException(false);

                //batchUpdateEntityLifecycle(lifeCycleDTO);

                List<EntityLifeCycleDTO> entityLifeCycleDTOS = lifeCycleDTO.getEntityLifeCycleDTOS();
                batchUpdateEntityLifecycle(entityLifeCycleDTOS, false, false, false);
            }
        }
    }

    /**
     * 修改图纸关联的零部件生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void componentsAssociatedDrawingsLifeStatus(String key, List<FlowObject> flowObjectList) {
        TyplmPartBomService typlmPartBomService = SpringUtil.getBean(TyplmPartBomService.class);
        TyplmCommonLifecycleService typlmCommonLifecycleService = SpringUtil.getBean(TyplmCommonLifecycleService.class);
        TyplmLocalePropertyValueService typlmLocalePropertyValueService = SpringUtil.getBean(
                TyplmLocalePropertyValueService.class);

        if (typlmPartBomService != null) {
            List<EntityLifeCycleDTO> entityLifeCycleList = new ArrayList();

            for (int a = 0; a < flowObjectList.size(); a++) {
                FlowObject flowObject = flowObjectList.get(a);
            }

        }
    }

    /**
     * 修改参考和描述文档关联的零部件生命周期状态
     *
     * @param key
     * @param flowObjectList
     */
    public void referenceDescribeAssociatedDrawingsLifeStatus(String key, List<FlowObject> flowObjectList) {

    }


    /**
     * 前端接口调用的方法
     *
     * @param lifeCycleDTO
     */
    public void batchUpdateEntityLifecycle(LifeCycleDTO lifeCycleDTO) throws Exception {
        TyplmLifecycleTemplateService typlmLifecycleTemplateService = SpringUtil.getBean(
                TyplmLifecycleTemplateService.class);
        List<EntityLifeCycleDTO> entityLifeCycleDTOS = lifeCycleDTO.getEntityLifeCycleDTOS();
        Boolean excludeException = lifeCycleDTO.getExcludeException();

        try {
            List<EntityMessageDTO> messageDTOS = typlmLifecycleTemplateService.batchUpdateEntityLifecycle(
                    entityLifeCycleDTOS, excludeException, false, false);
            TyplmAuditLogUtil.sendCollectInfo();
        } catch (Exception var7) {
            Exception exception = var7;
            if (!CollectionUtils.isEmpty(entityLifeCycleDTOS)) {
                TyAccountContext.cleanBizLogHolder();
                Iterator var5 = entityLifeCycleDTOS.iterator();

                while (var5.hasNext()) {
                    EntityLifeCycleDTO entityLifeCycleDTO = (EntityLifeCycleDTO) var5.next();
                    TyplmAuditLogUtil.errorInfo(entityLifeCycleDTO.getOid(), entityLifeCycleDTO.getOtype(),
                                                LogEventEnum.CHANGE_LC_STATE, exception);
                }
            }

            throw exception;
        }
    }

    public List<EntityMessageDTO> batchUpdateEntityLifecycle(List<EntityLifeCycleDTO> entityLifeCycleList,
                                                             Boolean excludeException, boolean ignoreNotExistState,
                                                             boolean ignoreCheckAccess) {
        TyplmLocalePropertyValueService typlmLocalePropertyValueService = SpringUtil.getBean(
                TyplmLocalePropertyValueService.class);
        if (CollectionUtils.isEmpty(entityLifeCycleList)) {
            return new ArrayList();
        } else {
            Map<IdentifierEntity, String> entityNewStateMap = new HashMap();
            Iterator var6 = entityLifeCycleList.iterator();

            while (var6.hasNext()) {
                EntityLifeCycleDTO entity = (EntityLifeCycleDTO) var6.next();
                TyplmEntityBaseUtil.checkParamNotNull(entity.getLifeCycleStageKey(), "LifeCycleStageKey");
                entityNewStateMap.put(new IdentifierEntity(entity.getOid(), entity.getOtype()),
                                      entity.getLifeCycleStageKey());
            }

            List<CTyEntityBaseDO> entityList = CommonUtil.getEntityListIgnoreNotExist(entityNewStateMap.keySet());
            List<TyTemplateAndStagesDTO> templateList = this.getTemplateAndStages(entityList);
            List<String> stageList = (List) entityLifeCycleList.stream().map(EntityLifeCycleDTO::getLifeCycleStageKey)
                    .distinct().collect(Collectors.toList());
            Map<String, String> localMap = typlmLocalePropertyValueService.queryLocaleValueByItem(new ArrayList(),
                                                                                                  "LifeCycleState",
                                                                                                  TyCommonExtUtil.getFrontLanguage());
            Iterator var10 = entityLifeCycleList.iterator();

            while (var10.hasNext()) {
                EntityLifeCycleDTO lifeCycleDTO = (EntityLifeCycleDTO) var10.next();
                CTyEntityBaseDO baseDO = (CTyEntityBaseDO) entityList.stream().filter((item) -> {
                    return item.getOid().equals(lifeCycleDTO.getOid());
                }).findAny().orElse(null);
                if (baseDO != null && baseDO instanceof ITyLifeCycleManaged) {
                    BigInteger lifecycletemplateoid = ((ITyLifeCycleManaged) baseDO).getLifecycletemplateoid();
                    String stagekey = ((ITyLifeCycleManaged) baseDO).getLifecyclestagekey();
                    List<TyLifecycleStateDTO> stateDTOList = this.getTyLifecycleStateDTOS(templateList,
                                                                                          lifecycletemplateoid,
                                                                                          stagekey);
                    if (CollectionUtils.isEmpty(stateDTOList)) {
                        throw LifeStageErrorCodeEnum.TEMPLATE_INCONSISTENT_CANNOT_OPERATE.getException(
                                new Object[]{localMap.get(lifeCycleDTO.getLifeCycleStageKey())});
                    }

                    boolean isMatch = stateDTOList.stream().anyMatch((item) -> {
                        return item.getCode().equals(lifeCycleDTO.getLifeCycleStageKey());
                    });
                    if (!isMatch) {
                        throw LifeStageErrorCodeEnum.LIFE_STAGE_CANNOT_BE_SET.getException(
                                new Object[]{localMap.get(lifeCycleDTO.getLifeCycleStageKey())});
                    }

                    TyplmAuditChangeLCLogDTO typlmAuditChangeLCLogDTO = new TyplmAuditChangeLCLogDTO();
                    typlmAuditChangeLCLogDTO.setNewLCKey(lifeCycleDTO.getLifeCycleStageKey());
                    typlmAuditChangeLCLogDTO.setOldLCKey(stagekey);
                    typlmAuditChangeLCLogDTO.setOid(lifeCycleDTO.getOid());
                    typlmAuditChangeLCLogDTO.setOtype(lifeCycleDTO.getOtype());
                    TyplmAuditLogUtil.info(typlmAuditChangeLCLogDTO, LogEventEnum.CHANGE_LC_STATE,
                                           String.format("生命周期状态 %s -> %s", localMap.get(stagekey),
                                                         localMap.get(lifeCycleDTO.getLifeCycleStageKey())));
                }
            }

            TyplmEntityBaseUtil.checkNotExistByIdentifier(entityNewStateMap.keySet(), entityList);
            return batchUpdateEntityLifecycle(entityLifeCycleList, entityList, entityNewStateMap, excludeException,
                                              ignoreNotExistState, ignoreCheckAccess);
        }
    }

    private List<TyTemplateAndStagesDTO> getTemplateAndStages(List<? extends CTyEntityBaseDO> entityList) {
        TyplmLifecycleStageTemplateService typlmLifecycleStageTemplateService = SpringUtil.getBean(
                TyplmLifecycleStageTemplateService.class);
        Stream var10000 = entityList.stream();
        ITyLifeCycleManaged.class.getClass();
        List<BigInteger> templateOidList = (List) var10000.filter(ITyLifeCycleManaged.class::isInstance).map((item) -> {
            return ((ITyLifeCycleManaged) item).getLifecycletemplateoid();
        }).distinct().collect(Collectors.toList());
        List<TyTemplateAndStagesDTO> templateList = typlmLifecycleStageTemplateService.selectTemplateAndStageByTemplateId(
                templateOidList);
        if (ObjectUtils.isEmpty(templateList)) {
            String[] templateArray = (String[]) templateOidList.stream().map((item) -> {
                return "ty.inteplm.lifecycle.CTyLifecycleTemplate:" + item;
            }).toArray((x$0) -> {
                return new String[x$0];
            });
            TyException.throwSingleTyExceptionArray(ResponseCodeEnum.BIZ_LIFECYCLETEMPLATE_NOT_FOUND, templateArray);
        }

        this.sortTemplateStageListbyTyTemplateAndStagesDTOList(templateList);
        return templateList;
    }

    private void sortTemplateStageListbyTyTemplateAndStagesDTOList(List<TyTemplateAndStagesDTO> templateList) {
        TyplmLifecycleStageService typlmLifecycleStageService = SpringUtil.getBean(TyplmLifecycleStageService.class);
        if (!CollectionUtils.isEmpty(templateList)) {
            templateList.forEach((item) -> {
                BigInteger templateoid = item.getTemplateoid();
                List<LifeCycleStageVO> lifeCycleStage = typlmLifecycleStageService.getLifeCycleStage(templateoid);
                List<TyLifeCycleStageTemplateDTO> stageList = item.getStageList();
                Map<BigInteger, TyLifeCycleStageTemplateDTO> toSortMap = (Map) stageList.stream().collect(
                        Collectors.toMap(CTyEntityBaseDO::getOid, Function.identity(), (v1, v2) -> {
                            return v2;
                        }));
                List<TyLifeCycleStageTemplateDTO> sortList = (List) lifeCycleStage.stream().map((data) -> {
                    return (TyLifeCycleStageTemplateDTO) toSortMap.get(data.getOid());
                }).collect(Collectors.toList());
                item.setStageList(sortList);
            });
        }
    }

    private List<TyLifecycleStateDTO> getTyLifecycleStateDTOS(List<TyTemplateAndStagesDTO> templateList,
                                                              BigInteger lifecycletemplateoid, String stagekey) {
        TyplmPhaseSuccessionMapper typlmPhaseSuccessionMapper = SpringUtil.getBean(TyplmPhaseSuccessionMapper.class);
        TyplmLocalePropertyValueService typlmLocalePropertyValueService = SpringUtil.getBean(
                TyplmLocalePropertyValueService.class);

        TyTemplateAndStagesDTO templateAndStagesDTO = (TyTemplateAndStagesDTO) templateList.stream().filter((item) -> {
            return item.getTemplateoid().equals(lifecycletemplateoid);
        }).findFirst().orElse(null);
        if (templateAndStagesDTO == null) {
            return Collections.emptyList();
        } else {
            List<TyLifeCycleStageTemplateDTO> stageList = templateAndStagesDTO.getStageList();
            TyLifeCycleStageTemplateDTO templateDTO = (TyLifeCycleStageTemplateDTO) stageList.stream().filter(
                    (item) -> {
                        return StringUtils.equals(item.getStagestate(), stagekey);
                    }).findFirst().orElse(null);
            if (templateDTO == null) {
                return Collections.emptyList();
            } else {
                List<EditStateChangeDTO> editStateChangeS = typlmPhaseSuccessionMapper.queryStageChangeList(
                        templateDTO.getOid());
                if (CollectionUtils.isEmpty(editStateChangeS)) {
                    return Collections.emptyList();
                } else {
                    List<BigInteger> oidList = (List) editStateChangeS.stream().filter((item) -> {
                        return StringUtils.equals(item.getLanguagekey(), "SET_STATE");
                    }).map(EditStateChangeDTO::getOid).collect(Collectors.toList());
                    List<TyLifeCycleStageTemplateDTO> setStageList = (List) stageList.stream().filter((item) -> {
                        return oidList.contains(item.getOid());
                    }).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(setStageList)) {
                        return Collections.emptyList();
                    } else {
                        Map<String, String> map = typlmLocalePropertyValueService.queryLocaleValueByItem(
                                (Collection) setStageList.stream().map(TyLifeCycleStageTemplateDTO::getStagestate)
                                        .collect(Collectors.toList()), "LifeCycleState",
                                TyCommonExtUtil.getFrontLanguage());
                        return (List) setStageList.stream().map((data) -> {
                            TyLifecycleStateDTO stateDTO = new TyLifecycleStateDTO();
                            stateDTO.setCode(data.getStagestate());
                            stateDTO.setName((String) map.get(data.getStagestate()));
                            return stateDTO;
                        }).collect(Collectors.toList());
                    }
                }
            }
        }
    }

    private List<EntityMessageDTO> batchUpdateEntityLifecycle(List<EntityLifeCycleDTO> entityLifeCycleList,
                                                              List<? extends CTyEntityBaseDO> entityList,
                                                              Map<IdentifierEntity, String> entityNewStateMap,
                                                              boolean excludeException, boolean ignoreNotExistState,
                                                              boolean ignoreCheckAccess) {
        TyplmPermissionsUtil typlmPermissionsUtil = SpringUtil.getBean(TyplmPermissionsUtil.class);

        if (!CollectionUtils.isEmpty(entityList) && !CollectionUtils.isEmpty(entityNewStateMap)) {
            List<EntityMessageDTO> messageDTOList = new ArrayList();
            this.checkIteratorStatus(entityList, messageDTOList);
            UserDO currentUser = CommonUtil.getUser();
            if (!ignoreCheckAccess) {
                List<String> statList = (List) entityList.parallelStream().map((entityx) -> {
                    return "设置状态";
                }).collect(Collectors.toList());
                List<EntityMessageDTO> messageDTOS = typlmPermissionsUtil.checkObjectPermissionAndGetExceptionMessage(
                        currentUser, entityList, statList);
                messageDTOList.addAll(messageDTOS);
            }

            Map<BigInteger, Map<String, TyLifeCycleStageTemplateDTO>> templateStagesMap = this.getTemplateStagesMap(
                    entityList);
            List<NewLifeCycleStateHistoryDTO> lifeCycleStateHistoryDTOS = new ArrayList();
            List<CTyEntityBaseDO> updateEntityList = new ArrayList();
            List<CTyEntityBaseDO> refreshTeamEntityList = new ArrayList();
            List<BigInteger> filterList = this.filterStateList(entityLifeCycleList);
            entityList = (List) entityList.stream().filter((entityx) -> {
                return filterList.contains(entityx.getOid());
            }).collect(Collectors.toList());
            Iterator var14 = entityList.iterator();

            while (var14.hasNext()) {
                CTyEntityBaseDO entity = (CTyEntityBaseDO) var14.next();
                String stateCode = (String) entityNewStateMap.get(
                        new IdentifierEntity(entity.getOid(), entity.getOtype()));
                if (!this.checkStateNotExist(entity, templateStagesMap, ignoreNotExistState, stateCode,
                                             messageDTOList)) {
                    TyLifeCycleStageTemplateDTO stageDTO = (TyLifeCycleStageTemplateDTO) ((Map) templateStagesMap.get(
                            ((ITyLifeCycleManaged) entity).getLifecycletemplateoid())).get(stateCode);
                    String lastState = ((ITyLifeCycleManaged) entity).getLifecyclestagekey();
                    if (!Objects.isNull(stageDTO)) {
                        ((ITyLifeCycleManaged) entity).setLifecyclestagekey(stateCode);
                        ((ITyLifeCycleManaged) entity).setLifecyclestageoid(stageDTO.getOid());
                        ((ITyLifeCycleManaged) entity).setLifecyclestageotype(stageDTO.getOtype());
                    }

                    if (entity instanceof ITyUpdator) {
                        ((ITyUpdator) entity).setUpdatoroid(currentUser.getOid());
                        ((ITyUpdator) entity).setUpdatorotype(currentUser.getOtype());
                    }

                    lifeCycleStateHistoryDTOS.add(this.newLifecycleHistory(lastState, stateCode, currentUser, entity));
                    updateEntityList.add(entity);
                    if ("ty.inteplm.doc.CTyDoc".equals(entity.getOtype())) {
                        refreshTeamEntityList.add(entity);
                    }
                    if ("ty.inteplm.cad.CTyCADDoc".equals(entity.getOtype())) {
                        refreshTeamEntityList.add(entity);
                    }
                }
            }

            return this.filterUpdateList(messageDTOList, excludeException, updateEntityList, refreshTeamEntityList,
                                         lifeCycleStateHistoryDTOS);
        } else {
            return new ArrayList();
        }
    }

    private void checkIteratorStatus(List<? extends CTyEntityBaseDO> cTyEntityBaseDOS,
                                     List<EntityMessageDTO> entityMessageDTOS) {
        Iterator var3 = cTyEntityBaseDOS.iterator();

        while (var3.hasNext()) {
            CTyEntityBaseDO cTyEntityBaseDO = (CTyEntityBaseDO) var3.next();
            if (cTyEntityBaseDO instanceof ITyLockable && "c/o".equalsIgnoreCase(
                    ((ITyLockable) cTyEntityBaseDO).getLockstateinfo())) {
                String type = (String) FolderQueryConstant.QUERY_OTYPE_TO_TYPE_MAP.getOrDefault(
                        cTyEntityBaseDO.getOtype(), cTyEntityBaseDO.getOtype());
                String displayName = CommonUtil.getEntityDisplayName(cTyEntityBaseDO);
                EntityMessageDTO entityMessageDTO = new EntityMessageDTO();
                entityMessageDTO.setIdentityStr(displayName);
                entityMessageDTO.setOid(String.valueOf(cTyEntityBaseDO.getOid()));
                entityMessageDTO.setType(type);
                String message = TyMessageUtil.getMessage(
                        ResponseCodeEnum.BIZ_LIFECYCLESTATE_CHANGE_FAIL_CHECKOUT.getLocaleKey(),
                        new String[]{displayName});
                entityMessageDTO.setMessage(message);
                entityMessageDTOS.add(entityMessageDTO);
            }
        }

    }

    private Map<BigInteger, Map<String, TyLifeCycleStageTemplateDTO>> getTemplateStagesMap(
            List<? extends CTyEntityBaseDO> entityList) {
        List<TyTemplateAndStagesDTO> templateList = this.getTemplateAndStages(entityList);
        Map<BigInteger, Map<String, TyLifeCycleStageTemplateDTO>> templateStatesMap = new HashMap();
        Iterator var4 = templateList.iterator();

        while (true) {
            TyTemplateAndStagesDTO dto;
            do {
                if (!var4.hasNext()) {
                    return templateStatesMap;
                }

                dto = (TyTemplateAndStagesDTO) var4.next();
            } while (TyplmEntityBaseUtil.checkEmptyAndRemoveNull(dto.getStageList()));

            Map<String, TyLifeCycleStageTemplateDTO> stateMap = (Map) templateStatesMap.computeIfAbsent(
                    dto.getTemplateoid(), (k) -> {
                        return new HashMap();
                    });
            Iterator var7 = dto.getStageList().iterator();

            while (var7.hasNext()) {
                TyLifeCycleStageTemplateDTO stageDTO = (TyLifeCycleStageTemplateDTO) var7.next();
                stateMap.put(stageDTO.getStagestate(), stageDTO);
            }
        }
    }

    public List<BigInteger> filterStateList(List<EntityLifeCycleDTO> entityLifeCycleList) {
        List<BigInteger> filterList = new ArrayList();
        entityLifeCycleList.forEach((entityLifeCycleDTO) -> {
            CTyEntityBaseDO entityBaseDO = CommonUtil.getEntity(
                    new IdentifierEntity(entityLifeCycleDTO.getOid(), entityLifeCycleDTO.getOtype()));
            if (entityBaseDO instanceof ITyLifeCycleManaged) {
                String oldLifecycleState = ((ITyLifeCycleManaged) entityBaseDO).getLifecyclestagekey();
                if (!oldLifecycleState.equals(entityLifeCycleDTO.getLifeCycleStageKey())) {
                    filterList.add(entityLifeCycleDTO.getOid());
                }
            }

        });
        return filterList;
    }

    private boolean checkStateNotExist(CTyEntityBaseDO entity,
                                       Map<BigInteger, Map<String, TyLifeCycleStageTemplateDTO>> templateStagesMap,
                                       boolean ignoreNotExistState, String stateCode,
                                       List<EntityMessageDTO> entityMessageDTOS) {
        if (!(entity instanceof ITyLifeCycleManaged)) {
            return true;
        } else {
            String type = (String) FolderQueryConstant.QUERY_OTYPE_TO_TYPE_MAP.getOrDefault(entity.getOtype(),
                                                                                            entity.getOtype());
            String displayName = CommonUtil.getEntityDisplayName(entity);
            EntityMessageDTO entityMessageDTO = new EntityMessageDTO();
            entityMessageDTO.setIdentityStr(displayName);
            entityMessageDTO.setOid(String.valueOf(entity.getOid()));
            entityMessageDTO.setType(type);
            BigInteger lifecycleTemplateOid = ((ITyLifeCycleManaged) entity).getLifecycletemplateoid();
            if (!templateStagesMap.containsKey(lifecycleTemplateOid)) {
                if (ignoreNotExistState) {
                    return true;
                }

                String message = TyMessageUtil.getMessage(
                        ResponseCodeEnum.BIZ_LIFECYCLETEMPLATE_NOT_FOUND.getLocaleKey(), new String[]{displayName});
                entityMessageDTO.setMessage(message);
                entityMessageDTOS.add(entityMessageDTO);
            }

            Map<String, TyLifeCycleStageTemplateDTO> stages = (Map) templateStagesMap.get(lifecycleTemplateOid);
            if (!stages.containsKey(stateCode)) {
                if (ignoreNotExistState) {
                    return true;
                }

                String message = TyMessageUtil.getMessage(
                        ResponseCodeEnum.BIZ_LIFECYCLESTATUS_NOT_IN_OPTIONAL_LIST.getLocaleKey(),
                        new String[]{displayName});
                entityMessageDTO.setMessage(message);
                entityMessageDTOS.add(entityMessageDTO);
            }

            return false;
        }
    }

    private NewLifeCycleStateHistoryDTO newLifecycleHistory(String lastStatus, String status, UserDO userDO,
                                                            CTyEntityBaseDO baseDO) {
        NewLifeCycleStateHistoryDTO newLifeCycleStateHistoryDTO = new NewLifeCycleStateHistoryDTO();
        newLifeCycleStateHistoryDTO.setAction(StatusActionEnum.SETSTATE);
        newLifeCycleStateHistoryDTO.setUserDO(userDO);
        newLifeCycleStateHistoryDTO.setBaseObject(baseDO);
        newLifeCycleStateHistoryDTO.setLifecyclestagekey(lastStatus);
        newLifeCycleStateHistoryDTO.setState(status);
        return newLifeCycleStateHistoryDTO;
    }

    public List<EntityMessageDTO> filterUpdateList(List<EntityMessageDTO> messageDTOList, boolean excludeException,
                                                   List<CTyEntityBaseDO> updateEntityList,
                                                   List<CTyEntityBaseDO> refreshTeamEntityList,
                                                   List<NewLifeCycleStateHistoryDTO> lifeCycleStateHistoryDTOS) {
        TyplmEntityBaseService typlmEntityBaseService = SpringUtil.getBean(TyplmEntityBaseService.class);
        TyplmLifeCycleHistoryService typlmLifeCycleHistoryService = SpringUtil.getBean(
                TyplmLifeCycleHistoryService.class);
        TyplmTeamForStageService typlmTeamForStageService = SpringUtil.getBean(TyplmTeamForStageService.class);
        excludeException = true;
        List<String> entityMessageOids = (List) messageDTOList.stream().map(EntityMessageDTO::getOid).collect(
                Collectors.toList());
        if (!excludeException) {
            if (!CollectionUtils.isEmpty(messageDTOList)) {
                return messageDTOList;
            }

            typlmEntityBaseService.batchUpdateEntityBase(updateEntityList, true);
            if (!CollectionUtils.isEmpty(lifeCycleStateHistoryDTOS)) {
                typlmLifeCycleHistoryService.newLifeCycleStateHistory(lifeCycleStateHistoryDTOS);
            }

            if (ObjectUtils.isNotEmpty(refreshTeamEntityList)) {
                typlmTeamForStageService.batchUpdateTeamByLifeStage(refreshTeamEntityList);
            }
        } else {
            List<CTyEntityBaseDO> filterUpdateEntityList = (List) updateEntityList.parallelStream().filter(
                    (updateEntity) -> {
                        return !entityMessageOids.contains(updateEntity.getOid().toString());
                    }).collect(Collectors.toList());
            List<CTyEntityBaseDO> filterRefreshTeamEntityList = (List) refreshTeamEntityList.parallelStream().filter(
                    (refreshTeamEntity) -> {
                        return !entityMessageOids.contains(refreshTeamEntity.getOid().toString());
                    }).collect(Collectors.toList());
            List<NewLifeCycleStateHistoryDTO> filterLifeCycleStateHistorys = (List) lifeCycleStateHistoryDTOS.parallelStream()
                    .filter((lifeCycleStateHistoryDTO) -> {
                        return !entityMessageOids.contains(
                                lifeCycleStateHistoryDTO.getBaseObject().getOid().toString());
                    }).collect(Collectors.toList());

            typlmEntityBaseService.batchUpdateEntityBase(updateEntityList, true);


            typlmEntityBaseService.batchUpdateEntityBase(filterUpdateEntityList, true);
            if (!CollectionUtils.isEmpty(filterLifeCycleStateHistorys)) {
                typlmLifeCycleHistoryService.newLifeCycleStateHistory(filterLifeCycleStateHistorys);
            }

            if (ObjectUtils.isNotEmpty(refreshTeamEntityList)) {
                typlmTeamForStageService.batchUpdateTeamByLifeStage(filterRefreshTeamEntityList);
            }
        }

        return new ArrayList();
    }

}
